<template>
	<view class="province-city-area">
		<view class="province-city-area-content flex-spb-cn" @click="onShowPicker">
			<template v-if="!value.length || !value[0] || !value[1] || !value[2]">
				<slot name="placeholder" v-if="$slots['placeholder']"></slot>
				<text v-else class="pl word-keep" :style="placeholderStyles">{{placeholder}}</text>
			</template>
			<template v-else>
				<slot v-if="$slots['default']"></slot>
				<view v-else-if="loaded" class="choose-label text-ellipsis" :style="labelStyles">
					<text>{{chooseData[0][nameField]}}</text>
					<text class="separator" :style="separatorStyles">{{separator}}</text>
					<text>{{chooseData[1][nameField]}}</text>
					<text class="separator" :style="separatorStyles">{{separator}}</text>
					<text>{{chooseData[2][nameField]}}</text>
				</view>
			</template>
			<text class="qh-rt-single right-icon" :class="icon"></text>
		</view>
		<qh-popup v-if="showPicker" v-model="showPicker" :title="title" @cancel="cancel" @confirm="confirm" :cancelText="clearable?'清空':'取消'"
			contentStyle="padding:0">
			<view class="picker-view-box">
				<picker-view indicator-style="{height: 50px}" indicator-class="picker-view-indicator-class" class="picker-view" :value="defaultIndex"
					@change="pickerChange">
					<picker-view-column v-for="(column, index) in columns" :key="index">
						<view class="picker-view-item" v-for="(item, i) in column" :key="i">{{item[nameField]}}</view>
					</picker-view-column>
				</picker-view>
			</view>
		</qh-popup>
	</view>
</template>

<script>
	export default {
		name: "province-city-area",
		props: {
			value: {
				type: Array,
				default () {
					return []
				},
			},
			keyField: {
				type: String,
				default: 'city_code',
			},
			nameField: {
				type: String,
				default: 'city_name',
			},
			title: {
				type: String,
				default: '选择省市区',
			}, //弹框标题
			separator: {
				type: String,
				default: '/'
			}, //分隔符
			placeholder: {
				type: String,
				default: '选择省市区'
			}, //占位符
			clearable: {
				type: Boolean,
				default: false,
			}, //是否能清除选项
			icon: {
				type: String,
				default: 'qh-rt-you'
			}, //右边的图标
			fontSize: {
				type: [String, Number],
				default: ''
			}, //字体大小，优先使用每个style里的字体大小
			labelStyle: {
				type: [String, Object],
				default () {
					return {}
				}
			}, //label的样式
			placeholderStyle: {
				type: [String, Object],
				default () {
					return {}
				}
			}, //占位符样式
			separatorStyle: {
				type: [String, Object],
				default () {
					return {}
				}
			}, //分割符样式
		},
		emits: ['update:value', 'change', 'input'],
		data() {
			return {
				showPicker: false,
				columns: [
					[],
					[],
					[]
				],
				defaultIndex: [0, 0, 0],
				loaded: false, //接口数据是否已加载完毕
				allCitys: [],
				cityCodes: null,
				cityNames: null,
				chooseData: [],
			};
		},
		computed: {
			labelStyles() {
				return this.handleFontSize(this.labelStyle);
			},
			placeholderStyles() {
				return this.handleFontSize(this.placeholderStyle);
			},
			separatorStyles() {
				return this.handleFontSize(this.separatorStyle);
			},
		},
		methods: {
			handleFontSize(styles) {
				let str = this.fontSize ? ('font-size:' + this.$getUnitSize(this.fontSize) + ';line-height:' + this.$getUnitSize(this.fontSize) + ';') : '';
				return str + this.$joinStyle(styles);
			},
			//打开弹窗
			onShowPicker() {
				this.showPicker = true;
			},
			//滚动选项
			pickerChange(e) {
				// console.log(e);
				if (e.detail.value[0] != this.defaultIndex[0]) {
					//第一列发生改变
					this.$set(this.columns, 1, this.handleCitys(this.allCitys[e.detail.value[0]].children));
					this.$set(this.columns, 2, this.allCitys[e.detail.value[0]].children[0].children);
					this.$nextTick(() => {
						this.$set(this.defaultIndex, 0, e.detail.value[0]);
						this.$set(this.defaultIndex, 1, 0);
						this.$set(this.defaultIndex, 2, 0);
					})
				} else if (e.detail.value[1] != this.defaultIndex[1]) {
					//第二列发生改变
					this.$set(this.columns, 2, this.allCitys[e.detail.value[0]].children[e.detail.value[1]].children)
					this.$nextTick(() => {
						this.$set(this.defaultIndex, 1, e.detail.value[1]);
						this.$set(this.defaultIndex, 2, 0);
					})
				} else {
					this.$set(this.defaultIndex, 2, e.detail.value[2]);
				}
			},
			//取消
			cancel(type) {
				if (type == 'cancel' && this.clearable) {
					//清空
					this.$emit('update:value', []);
					this.$emit('input', []);
					this.$emit('change', []);
					this.initColumn();
				}
				this.showPicker = false;
			},
			//确认
			confirm(close = true) {
				this.chooseData = [
					this.columns[0][this.defaultIndex[0]],
					this.columns[1][this.defaultIndex[1]],
					this.columns[2][this.defaultIndex[2]],
				];
				let value = [
					this.columns[0][this.defaultIndex[0]][this.keyField],
					this.columns[1][this.defaultIndex[1]][this.keyField],
					this.columns[2][this.defaultIndex[2]][this.keyField],
				];
				if (this.value[0] !== value[0] || this.value[1] !== value[1] || this.value[2] !== value[2]) {
					this.$emit('update:value', value);
					this.$emit('input', value);
					this.$emit('change', value);
				}
				if (close) this.showPicker = false;
			},
			//重置为第一项
			initColumn() {
				if (this.defaultIndex[0] != 0 || this.defaultIndex[1] != 0 || this.defaultIndex[2] != 0) {
					//重置为第一项
					this.defaultIndex[0] != 0 && this.$set(this.columns, 1, this.handleCitys(this.allCitys[0].children));
					if (this.defaultIndex[0] != 0 || this.defaultIndex[1] != 0) {
						this.$set(this.columns, 2, this.allCitys[0].children[0].children);
					}
					this.$nextTick(() => {
						this.$set(this.defaultIndex, 0, 0);
						this.$set(this.defaultIndex, 1, 0);
						this.$set(this.defaultIndex, 2, 0);
					})
				}
			},
			//提取数据
			handleCitys(arr) {
				let temp = [];
				arr.forEach((item) => {
					let obj = {};
					obj[this.keyField] = item[this.keyField];
					obj[this.nameField] = item[this.nameField];
					temp.push(obj);
				})
				return temp;
			},
			//根据名称或编码设置省市区
			searchValue() {
				console.log('searchValue')
				let index0 = this.allCitys.findIndex((item) => {
					return this.cityCodes ? (item[this.keyField] == this.cityCodes[0]) : (item[this.nameField] == this.cityNames[0]);
				})
				// console.log('index0', index0)
				if (!(index0 >= 0)) return;

				let index1 = this.allCitys[index0].children.findIndex((item) => {
					return this.cityCodes ? (item[this.keyField] == this.cityCodes[1]) : (item[this.nameField] == this.cityNames[1]);
				})
				// console.log('index1', index1)
				if (!(index1 >= 0)) return;

				let index2 = this.allCitys[index0].children[index1].children.findIndex((item) => {
					return this.cityCodes ? (item[this.keyField] == this.cityCodes[2]) : (item[this.nameField] == this.cityNames[2]);
				})
				// console.log('index2', index2)
				if (!(index2 >= 0)) return;

				this.$set(this.columns, 1, this.handleCitys(this.allCitys[index0].children))
				this.$set(this.columns, 2, this.allCitys[index0].children[index1].children)

				this.$nextTick(() => {
					this.$set(this.defaultIndex, 0, index0);
					this.$set(this.defaultIndex, 1, index1);
					this.$set(this.defaultIndex, 2, index2);
					// console.log(this.defaultIndex, this.columns)
					this.cityCodes = null;
					this.cityNames = null;
					this.$nextTick(() => {
						this.confirm(false)
					})
				})
			},
			//通过省市区的名称初始化选中项
			initValueForName(names) {
				console.log('initValueForName', names)
				this.cityNames = names;
				if (this.loaded) {
					this.searchValue();
				}
			},
			//通过省市区的编码初始化选中项
			initValueForCode(codes) {
				// console.log('initValueForCode', codes)
				this.cityCodes = codes;
				if (this.loaded) {
					this.searchValue();
				}
			},
			// 获取地址库
			async addressLib() {
				return new Promise((resolve, reject) => {
					getApp().globalData.sendRequest({
						url: '/Address/getCitys',
						type: 'post',
						success: (res) => {
							if (res.status == 1) {
								this.allCitys = res.data;
								this.$nextTick(() => {
									this.loaded = true;
									this.$set(this.columns, 0, this.handleCitys(res.data));
									if (this.cityCodes || this.cityNames) {
										this.searchValue();
									} else {
										this.$set(this.columns, 1, this.handleCitys(res.data[0].children));
										this.$set(this.columns, 2, res.data[0].children[0].children);
									}
									resolve();
								})
							} else {
								reject();
								uni.showModal({
									title: '提示',
									content: '查询失败',
									confirmColor: '#ff5c6d'
								});
							}
						}
					});
				})
			},
		},
		async created() {
			await this.$onLaunched;
			this.addressLib();
		},
		watch: {
			value: {
				deep: true,
				handler(n, o) {
					// console.log('watch:value', n, o)
					if (n[0] && n[1] && n[2]) {
						if (this.loaded) {
							let value = [
								this.columns[0][this.defaultIndex[0]][this.keyField],
								this.columns[1][this.defaultIndex[1]][this.keyField],
								this.columns[2][this.defaultIndex[2]][this.keyField],
							]
							if ((n[0] != value[0] || n[1] != value[1] || n[2] != value[2])) {
								this.initValueForCode(n)
							}
						} else {
							this.initValueForCode(n)
						}
					} else {
						this.initColumn();
					}
				},
			},
			// showPicker(n) {
			// 	if (n) {
			// 		console.log(this.defaultIndex, this.columns)
			// 	}
			// }
		}
	}
</script>

<style lang="scss">
	.province-city-area {
		background: transparent;
		line-height: 32rpx;
		max-width: 100%;

		.province-city-area-content {
			max-width: 100%;
		}

		.choose-label {
			font-size: 30rpx;
			color: #333333;
		}

		.separator {
			color: #929397;
			padding: 0 8rpx;
		}

		.picker-view-box {
			width: 100%;
			box-sizing: border-box;
			padding: 0 36rpx;

			.picker-view {
				width: 100%;
				height: 750rpx;
			}

			.picker-view-indicator-class {
				/* #ifdef MP-WEIXIN */
				height: 50px;
				/* #endif */
			}

			.picker-view-item {
				/* #ifdef MP-WEIXIN */
				height: 50px;
				line-height: 50px;
				/* #endif */
				align-items: center;
				justify-content: center;
				text-align: center;
				font-size: 30rpx;
				color: #1E1E1E;
			}
		}

		.right-icon {
			font-size: 22rpx;
			color: #929397;
			margin-left: 14rpx;
		}
	}
</style>
